package com.light.netty.client.security;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;
import java.util.List;

// 协议解码器
public class MessageDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {
        // 至少需要 id(4) + length(4) = 8 字节
        if (in.readableBytes() < 8) return;

        int id = in.readInt();                 // 读取 id
        int length = in.readInt();             // 读取 length
        if (in.readableBytes() < length) {   // 数据不足，回退索引
            in.resetReaderIndex();
            return;
        }
        String data = in.readBytes(length).toString(CharsetUtil.UTF_8); // 读取 data
        out.add(new MessageProtocol(id, data)); // 构建业务对象
    }
}